package com.example.demo.tree.t002;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName TreeTest
 * @Description: TODO
 * @Author Administrator
 * @Date 2021/10/14 23:52
 * @Version V1.0
 **/
public class TreeTest {
    public static void main(String[] args) {
        List<Tree> treeList = new ArrayList<>();
        Tree t1=new Tree();
        t1.setId("1");
        t1.setName("t1");
        t1.setParentId("0");
        treeList.add(t1);

        Tree t2 = new Tree();
        t2.setId("2");
        t2.setName("t2");
        t2.setParentId("0");
        treeList.add(t2);

        Tree t3 = new Tree();
        t3.setId("3");
        t3.setName("t3");
        t3.setParentId("1");
        treeList.add(t3);

        Tree t4 = new Tree();
        t4.setId("4");
        t4.setName("t4");
        t4.setParentId("1");
        treeList.add(t4);

        Tree t5 = new Tree();
        t5.setId("5");
        t5.setName("t5");
        t5.setParentId("3");
        treeList.add(t5);

        Tree t6 = new Tree();
        t6.setId("6");
        t6.setName("t6");
        t6.setParentId("2");
        treeList.add(t6);

        listToTree(treeList);
        System.out.println(JSONUtil.toJsonPrettyStr(treeList));

    }

    private static void listToTree(List<Tree> treeList) {
        for (Tree ele : treeList) {
            String parentId = ele.getParentId();
            if ("0".equals(parentId)) {
                // 是根元素的hua ,不做任何操作,如果是正常的for-i循环,可以直接continue.
            } else {
                // 如果ele是子元素的话 ,把ele扔到他的父亲的child数组中.
                for (Tree d : treeList) {
                    if (d.getId().equals(parentId)) {
                        List<Tree> children = d.getChildren();
                        if (CollectionUtil.isEmpty(children)){
                            children = new ArrayList<>();
                        }
                        children.add(ele);
                        d.setChildren(children);
                    }
                }
            }
        }
        for (int i = 0; i < treeList.size(); i++) {
            if (!"0".equals(treeList.get(i).getParentId())) {
                treeList.remove(i);
                i--;
            }
        }
    }


}
